<template>
  <div class="out-box">
    <el-row :gutter="0">
      <el-col :xs="8" :sm="8" :md="8" :lg="6" :xl="4">
        <el-card class="box-card" shadow="never">
          <div class="add-space-box" @click="newSpace">
            <div class="inner-box-top">
              <div class="text item">
                <div class="new-button">
                  <svg
                    class="icon"
                    style="width: 2.3em; height: 2.3em; vertical-align: middle; fill: currentColor; overflow: hidden"
                    viewBox="0 0 1024 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    p-id="3846"
                  >
                    <path
                      d="M512 512m-384 0a384 384 0 1 0 768 0 384 384 0 1 0-768 0Z"
                      fill="#fa8919"
                      p-id="3847"
                    ></path>
                    <path d="M469.333333 298.666667h85.333334v426.666666h-85.333334z" fill="#FDFDFD" p-id="3848"></path>
                    <path d="M725.333333 469.333333v85.333334H298.666667v-85.333334z" fill="#FDFDFD" p-id="3849"></path>
                  </svg>
                  <p>{{ this.$t("新建空间") }}</p>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col v-for="(item, index) in tableData" :key="index" :xs="8" :sm="8" :md="8" :lg="6" :xl="4">
        <el-card class="box-card" :class="{ 'pending-box-card': item.status !== 1 }" shadow="never">
          <div class="space-box" @click="openSpace(item)">
            <div class="inner-box-top">
              <div v-if="item.status !== 1" class="pending-review-banner">
                {{ utils.getDicLabel("reviewStatus", item.status) }}
              </div>
              <div class="text item over-ellipsis space-title" :title="item.name">
                {{ item.name }}
              </div>
              <div class="text item over-ellipsis space-desc" :title="item.spaceId">
                {{ item.spaceId }}
              </div>
              <!-- <div class="text item over-ellipsis space-desc" :title="item.desc">
                {{ item.info }}
              </div> -->

              <!-- <div class="text item over-ellipsis space-update-time">
                {{ item.updateTime }}
              </div> -->
            </div>
          </div>
          <div v-if="item.status === 1" class="inner-box-bottom">
            <div class="text button" @click="openDetail">
              <p>详情</p>
            </div>
            <div class="text button" @click="openDetail">
              <p>任务</p>
            </div>
            <div class="text button" @click="openSpaceUserDialog(item.spaceId)">
              <p>邀请</p>
            </div>
            <div class="text button" @click="openDetail">
              <p>模板</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog :title="dialog.title" :visible.sync="dialog.show" width="50%">
      <sec-form
        ref="newSpaceFormRef"
        v-if="dialog.show"
        :disabledProp="dialog.disableProp"
        :ruleForm="dialog.ruleForm"
        :rules="dialog.rules"
        :formData="dialog.formData"
      ></sec-form>
    </el-dialog>

    <el-dialog title="邀请新成员" :visible.sync="spaceUserDialog" width="60%">
      <sec-form
        ref="newSpaceUserFormRef"
        :ruleForm="userdialog.ruleForm"
        :optionData="userdialog.optionData"
        :rules="userdialog.rules"
        :formData="userdialog.formData"
      >
        <template v-slot:commonUser>
          <el-select
            v-model="commonUser"
            multiple
            filterable
            remote
            placeholder="请输入账号（邮箱前缀）"
            :remote-method="remoteMethodCommonUser"
            :loading="loading"
            @focus="onBlur('commonUser', 'commonUserRef')"
            ref="commonUserRef"
          >
            <el-option
              v-for="item in optionsCommonUser"
              :key="item.account"
              :label="`${item.name} - ${item.account}`"
              :value="item.account"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </template>
        <template v-slot:managerUser>
          <el-form-item>
            <el-select
              v-model="managerUser"
              multiple
              filterable
              remote
              placeholder="请输入账号（邮箱前缀）"
              :remote-method="remoteMethodManagerUser"
              :loading="loading"
              @focus="onBlur('managerUser', 'managerUserRef')"
              ref="managerUserRef"
            >
              <el-option
                v-for="item in optionsManagerUser"
                :key="item.account"
                :label="`${item.name} - ${item.account}`"
                :value="item.account"
                :disabled="item.disabled"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="margin: 10px 0 -20px -80px">
            <el-button @click="clearUserData">取 消</el-button>
            <el-button type="primary" @click="insertSpaceUser">确 定</el-button>
          </el-form-item>
        </template>
      </sec-form>
      <div style="padding: 20px">
        <!-- <div style="margin: 0 0 10px 0">
          <b>成员列表</b>
        </div> -->

        <sec-table :tableData="userdialog.tableData" :tableCol="userdialog.tableCol" :max-height="300"></sec-table>

        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          background
          :page-sizes="pageSizes"
          :page-size="pageSize"
          :layout="layout"
          :total="totalSize"
        >
        </el-pagination>
      </div>

      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="clearUserDialog">取 消</el-button>
        <el-button type="primary" @click="clearUserDialog">确 定</el-button>
      </span> -->

      <el-dialog title="修改用户权限" :visible.sync="spaceUserInnerDialog" append-to-body>
        <sec-form
          ref="userinnerdialogFormRef"
          :optionData="userinnerdialog.optionData"
          :ruleForm="userinnerdialog.ruleForm"
          :formData="userinnerdialog.formData"
        ></sec-form>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import {
  spacePageApi,
  spaceInsertApi,
  spaceUserInsertListApi,
  pageSpaceUserApi,
  updateSpaceUserApi,
  deleteSpaceUserApi,
  insertListApi,
  detailApi,
} from "api/dataCenter.js";
import { paginationMixin } from "@/mixins/pagination";
import Cookies from "js-cookie";
export default {
  mixins: [paginationMixin],
  data() {
    return {
      optionsCommonUser: [],
      optionsManagerUser: [],
      commonUser: [],
      managerUser: [],
      value: [],
      list: [],
      loading: false,
      //用户所选择的空间id
      spaceId: "",

      spaceUserDialog: false,
      spaceUserInnerDialog: false,

      tableData: [],
      userName: "",
      dialog: {
        title: this.$t("新建空间"),
        show: false,
        ruleForm: { spaceId: "", name: "", info: "" },
        rules: {
          spaceId: [
            { required: true, message: this.$t("请输入"), trigger: "change" },
            { validator: validSpace, trigger: "change" },
          ],
          name: [{ required: true, message: this.$t("请输入"), trigger: "change" }],
        },
        formData: [
          {
            type: "text",
            label: this.$t("空间Id"),
            prop: "spaceId",
          },
          {
            type: "text",
            label: this.$t("空间名称"),
            prop: "name",
          },
          {
            type: "textarea",
            label: this.$t("空间描述"),
            prop: "info",
          },

          {
            type: "operation",
            style: { "text-align": "right" },
            children: [
              {
                label: this.$t("确定"),
                click: () => {
                  if (this.$refs.newSpaceFormRef.submitForm()) {
                    this.upsertSpace();
                  }
                },
              },
              {
                label: this.$t("取消"),
                click: () => {
                  this.dialog.show = false;
                },
              },
            ],
          },
        ],
      },
      userdialog: {
        // ruleForm: { commonUser: "", managerUser: [] },
        optionData: { commonUser: [], managerUser: [] },
        formData: [
          {
            type: "slot",
            label: this.$t("邀请为用户"),
            prop: "commonUser",
          },
          {
            type: "slot",
            label: this.$t("邀请为管理员"),
            prop: "managerUser",
          },
          // {
          //   type: "select",
          //   label: this.$t("邀请为成员"),
          //   prop: "commonUser",
          //   filterable: true,
          //   remote: true,
          //   multiple: true,
          //   optionProps: {
          //     value: "account",
          //     label: (item) => {
          //       console.log(item);
          //       return `${item.account} -- ${item.name}`;
          //     },
          //   },

          //   remoteMethod: async (query) => {
          //     console.log(query);
          //     this.userdialog.optionData.commonUser = await this.$store.dispatch("getAccount", {
          //       fuzzyUsername: query,
          //     });
          //   },
          // },
          // {
          //   type: "select",
          //   label: this.$t("邀请为管理员"),
          //   prop: "managerUser",
          //   filterable: true,
          //   multiple: true,
          //   remote: true,
          //   optionProps: {
          //     value: "account",
          //     label: (item) => {
          //       console.log(item);
          //       return `${item.account} -- ${item.name}`;
          //     },
          //   },

          //   remoteMethod: async (query) => {
          //     console.log(query);
          //     this.userdialog.optionData.managerUser = await this.$store.dispatch("getAccount", {
          //       fuzzyUsername: query,
          //     });
          //   },
          // },
        ],

        spaceUserDialogId: "",
        tableData: [],
        tableCol: [
          { label: this.$t("空间id"), prop: "spaceId", width: 100 },
          { label: this.$t("账号"), prop: "userId" },
          { label: this.$t("姓名"), prop: "userName" },
          {
            label: this.$t("角色"),
            prop: "role",
            width: 80,
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel("spaceUserRole", row.role);
            },
          },
          { label: this.$t("创建时间"), prop: "createTime", width: 150 },

          {
            type: "operation",
            label: "操作",
            width: 150,
            children: [
              {
                label: "修改权限",
                disabled: (data) => {
                  return data.row.userId === this.userName;
                },
                click: (data) => {
                  console.log("data", data);
                  // 开启dialog
                  this.spaceUserInnerDialog = true;
                  // 查询用户
                  this.selectSpaceUser(data.row.id);
                },
              },
              {
                label: "删除权限",
                disabled: (data) => {
                  return data.row.userId === this.userName;
                },
                click: (data) => {
                  this.deleteClick(data.row);
                },
              },
            ],
          },
        ],
      },
      userinnerdialog: {
        ruleForm: {
          name: "",
          id: "",
          role: "",
          userId: "",
          userName: "",
          createTime: "",
          updateTime: "",
          info: "",
        },
        optionData: {
          role: [
            { label: "用户", value: 0 },
            { label: "管理员", value: 1 },
          ],
        },
        formData: [
          {
            type: "text",
            label: this.$t("账号"),
            prop: "userId",
            disabled: true,
            span: 12,
          },

          {
            type: "text",
            label: this.$t("姓名"),
            disabled: true,
            prop: "userName",
            span: 12,
            placeholder: " ",
          },
          {
            type: "select",
            label: this.$t("角色"),
            prop: "role",
            clearable: true,
            filterable: true,
          },
          {
            type: "textarea",
            label: this.$t("描述说明"),
            prop: "info",
          },
          {
            type: "text",
            label: this.$t("创建时间"),
            disabled: true,
            prop: "createTime",
            span: 12,
          },
          {
            type: "text",
            label: this.$t("修改时间"),
            disabled: true,
            prop: "updateTime",
            span: 12,
          },
          {
            type: "operation",
            style: { "text-align": "right" },
            children: [
              {
                label: this.$t("取消"),
                click: () => {
                  this.spaceUserInnerDialog = false;
                  //  刷新列表
                  this.openSpaceUserDialog(this.spaceId);
                },
              },
              {
                label: this.$t("确定"),
                click: () => {
                  if (this.$refs.userinnerdialogFormRef.submitForm()) {
                    this.editClick();
                  }
                },
              },
            ],
          },
        ],
      },
    };
  },
  created() {
    // 获取用户名信息
    this.userName = Cookies.get("_kylin_username");
  },
  mounted() {
    this.initPage();
  },
  methods: {
    onBlur(flag, ref) {
      this.$refs[ref].$refs.input.blur = () => {
        // 这里执行失焦的代码
        this.optionsCommonUser = [];
        this.optionsManagerUser = [];
      };
    },
    initPage() {
      this.getSpaceData();
    },
    getSpaceData() {
      //打开loading
      let loading = this.openLoading(".sec-main");
      spacePageApi({
        pageNum: 1,
        pageSize: 9999,
        requestData: this.userName || "root",
      }).then((res) => {
        console.log("[ res ] >", res);
        loading.close();
        let { list, pageNum, pageSize, pages, total } = res.data;
        this.tableData = list;
        this.totalSize = total;
      });
    },
    upsertSpace() {
      console.log("this add space");
      let { name, info, spaceId, id } = this.dialog.ruleForm;
      console.log("this.dialog?", this.dialog);
      spaceInsertApi({
        requestData: {
          spaceId: spaceId,
          name: name,
          info: info,
        },
      }).then((res) => {
        let state = this.message.state(res);
        if (!state) return;
        this.dialog.show = false;
        this.getSpaceData();
      });
    },
    newSpace() {
      this.dialog.show = true;
      // 初始化表单数据
      this.dialog.ruleForm = { spaceId: "", name: "", info: "" };
    },

    openSpace(space) {
      if (space.status === 1) {
        this.$router.push({
          name: "touchList",
          params: { spaceId: space.spaceId },
        });
      } else {
        // this.message.info({
        //   message: this.$t("审核中，有问题请联系"),
        // });

        const h = this.$createElement;
        this.message.info({
          message: h("p", null, [
            h("span", { style: { color: "#909399" } }, this.$t("审核中，有问题请联系")),
            h(
              "a",
              {
                attrs: {
                  href: "dchat://im/start_conversation?name=zhangfuli",
                },
              },
              "管理员",
            ),
          ]),
        });
        // this.$message({
        //   message: h("p", null, [
        //     h("span", { attrs: { class: "el-message__content" } }, this.$t("审核中，有问题请联系")),
        //     h(
        //       "a",
        //       {
        //         attrs: {
        //           href: "dchat://im/start_conversation?name=zhangfuli",
        //         },
        //       },
        //       "管理员",
        //     ),
        //   ]),
        //   type: "info",
        // });
      }
    },
    openDetail(obj) {
      console.log(obj);
      this.message.info({
        message: this.$t("快捷按键开发中，敬请期待"),
      });
    },

    spaceUserInsertList(obj) {
      spaceUserInsertListApi({}).then((res) => {});
    },

    async remoteMethodCommonUser(query) {
      let data = await this.$store.dispatch("getAccount", {
        fuzzyUsername: query,
      });
      data.forEach((element) => {
        let set = new Set(this.managerUser);
        element.disabled = set.has(element.account);
      });
      this.optionsCommonUser = data;
      console.log("111", this.optionsCommonUser);
    },

    async remoteMethodManagerUser(query) {
      let data = await this.$store.dispatch("getAccount", {
        fuzzyUsername: query,
      });
      data.forEach((element) => {
        let set = new Set(this.commonUser);
        element.disabled = set.has(element.account);
        //element.disabled = false;
      });
      this.optionsManagerUser = data;
      console.log(this.optionsManagerUser);
    },

    handleCurrentChange(val) {
      this.page = val;
      this.openSpaceUserDialog(this.spaceId);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.openSpaceUserDialog(this.spaceId);
    },

    openSpaceUserDialog(spaceId) {
      this.spaceUserDialog = true;

      // 设置spaceid
      this.spaceId = spaceId;
      //加载列表数据
      (this.userdialog.spaceUserDialogId = spaceId), this.getSpaceUserDialog();
    },

    getSpaceUserDialog() {
      pageSpaceUserApi({
        pageNum: this.page,
        pageSize: this.pageSize,
        requestData: this.userdialog.spaceUserDialogId,
      }).then((res) => {
        let { list, total } = res.data;
        this.userdialog.tableData = list;
        this.totalSize = total;
      });
    },
    // 查询用户详情
    selectSpaceUser(id) {
      detailApi({
        requestData: id,
      }).then((res) => {
        this.userinnerdialog.ruleForm = res.data;
      });
    },
    // todo 修改用户权限
    editClick() {
      let { id, role, info, userId, spaceId } = this.userinnerdialog.ruleForm;
      updateSpaceUserApi(
        {
          requestData: {
            id: id,
            userId: userId,
            spaceId: spaceId,
            role: role,
            info: info,
          },
        },
        {
          spaceId: this.spaceId,
        },
      ).then((res) => {
        let state = this.message.state(res);
        if (!state) return;
        this.selectSpaceUser(id);
        this.spaceUserInnerDialog = false;

        //  刷新列表
        this.openSpaceUserDialog(this.spaceId);
      });
    },

    // 剔除用户
    deleteClick(row) {
      this.utils.$confirm({ content: "确定删除此用户权限吗？" }, () => {
        deleteSpaceUserApi(
          {
            requestData: {
              userId: row.userId,
              spaceId: row.spaceId,
            },
          },
          {
            spaceId: this.spaceId,
          },
        ).then((res) => {
          let state = this.message.state(res);
          if (!state) return;
          this.openSpaceUserDialog(this.spaceId);
        });
      });
    },

    // 批量新增用户
    insertSpaceUser() {
      // todo 设置请求头 spaceid
      var spaceId = this.spaceId;
      // 设置用户
      var user = this.commonUser.map(function (e) {
        return {
          userId: e,
          spaceId: spaceId,
          role: 0,
        };
      });
      // 设置管理员
      var managerUser = this.managerUser.map(function (e) {
        return {
          userId: e,
          spaceId: spaceId,
          role: 1,
        };
      });
      //合并数组
      user.push.apply(user, managerUser);

      insertListApi(
        {
          requestData: user,
        },
        {
          spaceId: spaceId,
        },
      ).then((res) => {
        let state = this.message.state(res);
        if (!state) return;
        //清空数据
        this.clearUserData();
        // 刷新列表
        this.openSpaceUserDialog(this.spaceId);
      });
    },
    // 清空用户数据用户
    clearUserData() {
      this.commonUser = [];
      this.managerUser = [];
      // this.$refs.newSpaceFormRef.resetForm();
    },
    // 取消dialog
    clearUserDialog() {
      this.spaceUserDialog = false;
    },
  },
};
// 校验新建空间表单数据
let validSpace = (rule, value, callback) => {
  let isSpace = /^\w{6,20}$/.test(value);
  if (isSpace) {
    console.log("isspace?", isSpace);
    callback();
  } else {
    console.log("isspace?", isSpace);
    callback(new Error("6-20位字符,可使用大小写字母、数字、下划线"));
  }
};
</script>

<style lang="scss">
.out-box {
  padding: 20px;
  min-width: 825px;
  .add-space-box,
  .space-box {
    position: relative;
    height: 100%;
    widows: 100%;
  }
  /* .add-space-box::before,
.space-box::before {
  content: "";
  position: absolute;
  top: -10px;
  right: -10px;
  bottom: -10px;
  left: -10px;
} */
  /* section :is(div) {
  border: 1px navajowhite solid;
} */
  .text {
    font-size: 12px;
    color: black;
    user-select: none;
  }
  .space-title {
    font-size: 18px;
    font-weight: bold;
  }
  .space-desc {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.8);
    /* display: none; */
  }
  .space-update-time {
    font-size: 10px;
    font-display: none;
    text-align: right;
  }
  .button {
    width: 100%;
  }
  .button:hover {
    color: #fa8919;
  }
  /* .item {
  padding: 18px 0;
} */
  .el-col {
    min-width: 200px;
  }
  .box-card {
    cursor: pointer;
    text-align: center;
    margin: 20px auto;
    width: 260px;
    height: 130px;
    border: 1px solid rgba(128, 128, 128, 0.18);
    border-radius: 12px;
    -webkit-border-radius: 12px;
    overflow: hidden;
  }
  .el-card__body {
    height: 100%;
    position: relative;
    padding: 0px;
  }
  .box-card:hover {
    border: 1px solid #fa8919;
    box-shadow: 0 1px 5px rgb(0 21 41 / 10%);
    -webkit-box-shadow: 0 1px 5px rgb(0 21 41 / 10%);
  }
  .pending-box-card:hover {
    border: 1px solid rgb(180, 180, 180);
  }
  .inner-box-top {
    padding: 30px 20px;
  }
  .inner-box-bottom {
    position: absolute;
    bottom: -50px;
    display: flex;
    justify-content: space-around;
  }

  .pending-review-banner {
    width: 100%;
    background-color: rgba(180, 180, 180, 0.8);
    color: white;
    transform: rotate(45deg);
    position: absolute;
    top: 20px;
    right: -100px;
    user-select: none;
  }
  p {
    font-size: 12px;
  }
  .box-card:hover .inner-box-bottom {
    border-block-start: 1px solid #fa8919;
    bottom: 0px;
    left: 15px;
    right: 15px;
    transition: all 230ms cubic-bezier(0.65, 0.5, 0.233, 0);
  }
  /* .box-card:hover .space-desc {
  display: block;
} */
}
</style>
